<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\model\AdminMember as MemberModel;
use app\common\model\AdminMemberLevel as LevelModel;
use think\Db;

/**
 * 会员管理控制器
 * @package app\admin\controller
 */
class Member extends Admin
{

    /**
     * 会员列表
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function index($q = '')
    {
        $map = [];
        if ($q) {
            if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $q)) {// 邮箱
                $map['email'] = $q;
            } elseif (preg_match("/^1\d{10}$/", $q)) {// 手机号
                $map['mobile'] = $q;
            } else {// 用户名、昵称
                $map['username'] = ['like', '%'.$q.'%'];
            }
        }

        $data_list = MemberModel::where($map)->paginate();
        // 分页
        $pages = $data_list->render();
        $this->assign('data_list', $data_list);
        $this->assign('pages', $pages);
        return $this->fetch('index');
    }

    /**
     * 添加会员
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty( $data['start_time'])){
                unset( $data['start_time']);
            }else{
                $data['start_time'] = strtotime($data['start_time']);
            }

            // 验证
            $result = $this->validate($data, 'AdminMember');
            if($result !== true) {
                 $this->error($result);
            }
            $database = $data['db_name'];
            // 验证数据库是否可连接
            $dbString2 = sprintf('mysql://%s:%s@%s:%d/%s#utf8', $data['db_username'], $data['db_password'],$data['db_host'], $data['db_port'],'');
             $db_connect2 = Db::connect($dbString2);

            // 检测数据库连接
            try{
                $db_connect2->execute('select version()');
            }catch(\Exception $e){
                $this->error('数据库连接失败，请检查数据库配置！');
            }

            // 创建数据库
            if (!$db_connect2->execute("CREATE DATABASE IF NOT EXISTS `{$database}` DEFAULT CHARACTER SET utf8")) {
                 $this->error($db_connect2->getError());
            }
            $dbString = sprintf('mysql://%s:%s@%s:%d/%s#utf8', $data['db_username'], $data['db_password'],$data['db_host'], $data['db_port'],$database);
            $sql_file = APP_PATH.'admin/sql/installUser.sql';

            if (file_exists($sql_file)) {

                $sql = file_get_contents($sql_file);
                $sql_list = parse_sql($sql, 0, ['hisiphp_' => 'em_']);
                if ($sql_list) {
                    $sql_list = array_filter($sql_list);

                    foreach ($sql_list as $v) {

                        try {
                            Db::connect($dbString)->execute($v);
                        } catch(\Exception $e) {

                            $this->error('导入SQL失败，请检查install.sql的语句是否正确');
                        }
                    }
                }
            }
            $inUser['salt'] = rand(1000,9999);
            $inUser['loginName'] = $data['name'];
            $inUser['password'] = md5(md5($data['password']).$inUser['salt']);
            $inid = Db::connect($dbString)->table('em_user')->insertGetId($inUser);
            $whereup['id'] = $inid;
            $up1['as_name'] = $inid;
            Db::connect($dbString)->table('em_user')->where($whereup)->update($up1);
            unset($data['id']);
            if (!MemberModel::create($data)) {
                return $this->error('添加失败！');
            }
            return $this->success('添加成功。');
        }

        $this->assign('level_option', LevelModel::getOption());
        return $this->fetch('form');
    }

    /**
     * 修改会员
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function edit($id = 0)
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty( $data['start_time'])){
                unset( $data['start_time']);
            }else{
                $data['start_time'] = strtotime($data['start_time']);
            }

            if ($data['mobile'] == 0) {
                unset($data['mobile']);
            }
            // 验证
            $result = $this->validate($data, 'AdminMember.update');
            if($result !== true) {
                return $this->error($result);
            }
            if (!MemberModel::update($data)) {
                return $this->error('修改失败！');
            }
            return $this->success('修改成功。');
        }

        $row = MemberModel::where('id', $id)->find()->toArray();
        if($row['start_time']!=null){
            $row['start_time'] = date('Y-m-d',$row['start_time']);
        }
        $this->assign('data_info', $row);
        $this->assign('level_option', LevelModel::getOption($row['level_id']));
        return $this->fetch('form');
    }
    /**
     * 会员模块
     */
    public function module($id = 0){
        $this->assign('id',$id);
       return $this->fetch();
    }
    //获取模板
    public function getData(){
        $data = Db::name('nav')->field('id,nav_name,pid')->select();
        return $data;
    }
    //获取勾选模板
    public function getCheck()

    {   $id = $this->request->get('id');
        $where['uid'] = $id;
        $row =  Db::name('user_module')->where($where)->find();
        if (count($row)>0){
            $retData = json_decode($row['module'],true);
            return $retData;
        }

    }
    /**
    * 用户模块修改数据保存
    */
    public function save()
    {

        $post = $this->request->post();
        $accessIds = empty($post['values']) ? [] : $post['values'];
        $accessIds = array_map(function($accessId) {return intval($accessId);}, $accessIds);
        $where['uid'] = $post['uid'];
        $saveData['module'] = json_encode($accessIds,true);
        $data = Db::name('user_module')->where($where)->find();
        $iwhere['id'] = ['in',$accessIds];
        $inData = Db::name('nav')->where($iwhere)->select();
        if(count($data)>0){
            Db::name('user_module')->where($where)->update($saveData);
        }else{
            $saveData['uid'] = $post['uid'];
            Db::name('user_module')->insertGetId($saveData);
        }
        $whereAdmin['id'] = $post['uid'];
        $user = Db::name('admin_member')->where($whereAdmin)->find();
        if($user){

            $dbString = sprintf('mysql://%s:%s@%s:%d/%s#utf8', $user['db_username'], $user['db_password'],

                $user['db_host'], $user['db_port'], $user['db_name']);

                Db::connect($dbString)->query($sql = 'TRUNCATE table `em_nav`');


                $add = Db::connect($dbString)->table('em_nav')->insertAll($inData);
                if($add){
                    $this->jsonReturn(0,'操作成功');
                }

        }


    }
    /**
     * 会员列表弹窗
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function pop() {
        $q = input('param.q/s');
        $callback = input('param.callback/s');
        if (!$callback) {
            echo '<br><br>callback为必传参数！';
            exit;
        }

        $map = [];
        if ($q) {
            if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $q)) {// 邮箱
                $map['email'] = $q;
            } elseif (preg_match("/^1\d{10}$/", $q)) {// 手机号
                $map['mobile'] = $q;
            } else {// 用户名、昵称
                $map['username'] = ['like', '%'.$q.'%'];
            }
        }
        
        $data_list = MemberModel::where($map)->paginate(10, true);
        // 分页
        $pages = $data_list->render();
        $this->assign('data_list', $data_list);
        $this->assign('pages', $pages);
        $this->assign('callback', $callback);
        $this->view->engine->layout(false);
        return $this->fetch();
    }

    // +----------------------------------------------------------------------
    // | 会员等级
    // +----------------------------------------------------------------------

    /**
     * 会员等级列表
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function level()
    {
        $data_list = LevelModel::field('id,name,intro,discount,min_exper,max_exper,ctime,default,status')->paginate();
        // 分页
        $pages = $data_list->render();
        $this->assign('data_list', $data_list);
        $this->assign('pages', $pages);
        return $this->fetch();
    }

    /**
     * 添加会员等级
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function addLevel()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AdminMemberLevel');
            if($result !== true) {
                return $this->error($result);
            }
            unset($data['id']);
            if (!LevelModel::create($data)) {
                return $this->error('添加失败！');
            }
            // 更新缓存
            cache('system_member_level', LevelModel::getAll());
            return $this->success('添加成功。');
        }

        return $this->fetch('levelform');
    }

    /**
     * 修改会员等级
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function editLevel($id = 0)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'AdminMemberLevel');
            if($result !== true) {
                return $this->error($result);
            }
            if (!LevelModel::update($data)) {
                return $this->error('修改失败！');
            }
            // 更新缓存
            cache('system_member_level', LevelModel::getAll());
            return $this->success('修改成功。');
        }
        $row = LevelModel::where('id', $id)->find()->toArray();

        $this->assign('data_info', $row);
        return $this->fetch('levelform');
    }

    /**
     * 删除会员等级
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function delLevel()
    {
        $ids = input('param.ids/a');
        $model = new LevelModel;
        if (!$model->del($ids)) {
            return $this->error($model->getError());
        }
        return $this->success('删除成功');
    }

    /**
     * 设置默认等级
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function setDefault($id = 0)
    {
        LevelModel::update(['default' => 0], ['id' => ['neq', $id]]);
        if (LevelModel::where('id', $id)->setField('default', 1) === false) {
            return $this->error('设置失败！');
        }

        return $this->success('设置成功。');
    }
}
